﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;

namespace TransactionServer.CRMActivities
{
    class CRMEntityMetadataCache : Dictionary<string, EntityMetadata>
    {
        CRMConnector connector = null;
        private object syncRoot = new object();

        public CRMEntityMetadataCache(CRMConnector connector)
        {
            this.connector = connector;
        }

        public EntityMetadata this[string key] 
        { 
            get
            {
                lock (syncRoot)
                {
                    if (!base.ContainsKey(key))
                    {
                        var rerq = new RetrieveEntityRequest { EntityFilters = EntityFilters.Attributes | EntityFilters.Relationships, LogicalName = key };
                        var rersp = (RetrieveEntityResponse)connector.crmService.Execute(rerq);
                        base[key] = rersp.EntityMetadata;
                    }
                    return base[key];
                }
            } 
        }
    }
}
